<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['miniprogram:user:create']"
        >
          <Icon icon="ep:plus" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="用户ID" align="center" prop="id" />
      <el-table-column label="头像" align="center" prop="avatar" width="80">
        <template #default="scope">
          <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="头像" class="w-8 h-8 rounded-full" />
          <el-avatar v-else :size="32" :src="scope.row.avatar">
            <Icon icon="ep:user-filled" />
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="phone" />



      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button
              type="primary"
              link
              @click="openDetail(scope.row)"
              v-hasPermi="['miniprogram:user:query']"
            >
              <Icon icon="ep:view" />详情
            </el-button>
            <el-button
              type="primary"
              link
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['miniprogram:user:update']"
            >
              <Icon icon="ep:edit" />修改
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['miniprogram:user:delete']"
            >
              <Icon icon="ep:delete" />删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />

  <!-- 用户详情对话框 -->
  <el-dialog v-model="detailVisible" title="用户详情" width="800px" append-to-body>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="用户ID">{{ detailData.id }}</el-descriptions-item>
      <el-descriptions-item label="用户昵称">{{ detailData.nickname }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ detailData.phone }}</el-descriptions-item>
      <el-descriptions-item label="性别">
        <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="detailData.gender" />
      </el-descriptions-item>
      <el-descriptions-item label="头像">
        <img v-if="detailData.avatar" :src="detailData.avatar" alt="头像" class="w-16 h-16 rounded-full" />
        <span v-else>暂无头像</span>
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="detailData.status === 0 ? 'success' : 'danger'">
          {{ detailData.status === 0 ? '正常' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="最后登录IP">{{ detailData.loginIp || '暂无' }}</el-descriptions-item>
      <el-descriptions-item label="最后登录时间">{{ formatDate(detailData.loginDate) || '暂无' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间" :span="2">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import * as UserApi from '@/api/miniprogram/user'
import UserForm from './UserForm.vue'

defineOptions({ name: 'MiniProgramUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: undefined,
  phone: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const formRef = ref() // 表单 Ref
const detailVisible = ref(false) // 详情对话框的是否展示
const detailData = ref({}) // 详情数据

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.records || data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 状态点击处理 */
const handleStatusClick = async (row: any) => {
  const currentStatus = Number(row.status)
  const newStatus = currentStatus === 0 ? 1 : 0
  try {
    const text = newStatus === 0 ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.nickname + '"用户吗?')
    await UserApi.updateUserStatus(row.id, newStatus)
    row.status = newStatus
    message.success(text + '成功')
  } catch {
    // 用户取消操作，状态保持不变
  }
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 详情操作 */
const openDetail = async (row: any) => {
  detailData.value = await UserApi.getUser(row.id)
  detailVisible.value = true
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>